import AgentService from '@/modules/Agent';

export function sendMessageToRecord(type: string, msg: any, user: any) {
	type = type ? type : 'text';
	let message = {
		type: '',
		clientId: '',
		date: new Date(),
		from: '',
		label: '',
		fromUser: {},
		data: ''
	};
	message.type = type;
	message.clientId = user.clientId || '';
	message.date = getCurrentDate();

	message.from = user.id;
	message.label = user.role;
	message.fromUser = {
		id: user.id,
		name: user.userName,
		avatar: user.picture || user.avatar,
		isRobot: user.isRobot || false
	};
	message.data = formatMessage(type, msg);
	return message;
}

/**
 * 格式化消息
 * @param { String } type 消息类型
 * @param { Object } msg 消息体
 * @returns 格式化后消息体
 */
export function formatMessage(type: string, msg: any) {
	console.log(msg);
	let result: any = '';
	switch (type) {
		case 'text':
			result = msg.text ? msg.text : msg.data ? (msg.data === 'silence-msg' ? '- -' : msg.data) : msg;
			break;
		case 'link':
			if (msg.data) {
				result = { type: msg.data.type, url: msg.data.url, name: msg.data.name, size: msg.data.size, suffix: msg.data.suffix };
			} else {
				result = { type: msg.type, url: msg.url, name: msg.name, size: msg.size, suffix: msg.suffix ? msg.suffix : '' };
			}

			break;
		default:
			result = '';
			break;
	}
	return result;
}

// 根据消息 from，筛选访客信息
export function getCustomerInfo(from: string, members: any) {
	let clients = members.map((client: any) => {
		return {
			id: client.user.id,
			org: client.user.org,
			role: client.role,
			clientId: client.id,
			userName: client.user.name,
			isRobot: client.user.profile && client.user.profile.isRobot ? client.user.profile.isRobot : false
		};
	});

	return clients.find((agent: { clientId: string }) => agent.clientId === from);
}

export function formatSessionMessageRecords(records: any[]) {
	let map = new Map();
	let result: {}[] = [];
	records.forEach((msg: any) => {
		if (msg.msgType === 'peer-status' && msg.data.status === 'joined') {
			let user = { clientId: msg.data.id, role: msg.data.role, id: msg.data.user.id, userName: msg.data.user.name, isRobot: msg.data.user.profile.isRobot || false };
			map.set(msg.data.id, user);
		}
		if (msg.fromClientId === 'system') {
			let data = systemSessionRecord(msg.data);
			result.push(data);
		}
		if (msg.msgType === 'text' || msg.msgType === 'link') {
			let data = filterClientMessage(msg, map);
			result.push(data);
		}
	});
	return result;
}

export function filterClientMessage(data: any, map: Map<any, any>) {
	let message = {
		type: '',
		id: '',
		date: data.createdAt,
		from: '',
		label: '',
		fromUser: {},
		data: ''
	};
	message.type = formatMessageType(data);
	message.id = data.fromClientId || '';
	message.date = data.createdAt || getCurrentDate();
	message.from = data.fromUserId || '';
	message.label = data.fromUserRole || '';
	message.fromUser = {
		id: data.fromUserId ? data.fromUserId.id : '',
		name: data.fromUserName || '',
		avatar: data.fromUserAvatar || '',
		isRobot: map.get(data.fromClientId).isRobot
	};
	message.data = formatMessage(message.type, data);
	return message;
}

export function systemSessionRecord(data: { status: any; id?: any; role?: any; user?: { id: any; name: any; profile: { isRobot: any } }; cmd?: string; data?: any; at?: any }) {
	let message = {
		type: '',
		id: '',
		date: '',
		from: '',
		label: '',
		fromUser: {},
		data: ''
	};
	message.type = 'text';
	message.id = '';
	message.date = data.at;
	message.from = 'stytem';
	message.label = 'system';
	message.fromUser = {
		id: '',
		name: '系统消息',
		avatar: ''
	};
	message.data = `${getUsertName(data)} ${getUsertStatus(data.status)}`;
	return message;
}

export function getUsertName(data: any) {
	let result = '';
	switch (data.role) {
		case 'agent':
			result = `坐席<${data.user.name}>`;
			break;
		case 'customer':
			result = `用户<${data.user.name}>`;
			break;
		default:
			result = '';
			break;
	}
	return result;
}

/**
 * 留痕会话中，坐席加入 / 离开会话的消息
 * @param { Object } user 用户数据
 * @returns { Object } 消息体
 */
export function userInSessionRecord(user: any) {
	let message = {
		type: '',
		id: '',
		date: '',
		from: '',
		label: '',
		fromUser: {},
		data: ''
	};
	message.type = 'text';
	message.id = '';
	message.date = user.at;
	message.from = 'stytem';
	message.label = 'system';
	message.fromUser = {
		id: '',
		name: '系统消息',
		avatar: ''
	};
	let role = user.role === 'customer' ? '用户' : '坐席';
	message.data = `${role}<${user.user.name}>${getUsertStatus(user.status)}`;
	return message;
}

/**
 *
 * @param { String } status 坐席状态
 * @returns
 */
export function getUsertStatus(status: any) {
	let result = '';
	switch (status) {
		case 'joined':
			result = '加入会话';
			break;
		case 'quit':
			result = '离开会话';
			break;
		default:
			result = '';
			break;
	}
	return result;
}

export function formatMessageType(data: any) {
	let type = '';
	switch (data.msgType) {
		case 'peer-response':
			type = data.data.cmd;
			break;
		case 'peer-cmd':
			type = data.data.cmd;
			break;
		default:
			type = data.msgType;
			break;
	}
	return type;
}

export function getCurrentDate() {
	return new Date();
}

/** 进入全屏 */
export function launchFullScreen(element: HTMLElement) {
	if (element.requestFullscreen) {
		element.requestFullscreen();
	} else if (element.mozRequestFullScreen) {
		element.mozRequestFullScreen();
	} else if (element.webkitRequestFullscreen) {
		element.webkitRequestFullscreen();
	} else if (element.msRequestFullscreen) {
		element.msRequestFullscreen();
	}
}

/** 检测设备是否支持全屏 */
export function fullscreenEnabled() {
	return document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullscreenEnabled || document.msFullscreenEnabled;
}

/**
 * 退出全屏模式
 */
export function cancelFullScreen() {
	if (document.exitFullscreen) {
		document.exitFullscreen();
	} else if (document.mozExitFullscreen) {
		document.mozExitFullscreen();
	} else if (document.webkitExitFullscreen) {
		document.webkitExitFullscreen();
	} else if (document.msExitFullscreen) {
		document.msExitFullscreen();
	}
}

/**
 * 防抖函数
 * @param { Fucntion } callback  回调函数
 * @param {*} time 时长
 * @returns
 */
export function debounce(callback: (value?: string) => void, time: number) {
	// 声明一个 timerId 用来存储定时器
	let timerId: any | null = null;
	return (e?: React.ChangeEvent<HTMLInputElement>) => {
		// 判断 timerId 是否存在, 存在则清除
		if (timerId) {
			clearTimeout(timerId);
		}
		timerId = setTimeout(() => {
			if (e && e.target.value) {
				callback(e.target.value);
			} else {
				callback();
			}

			// 重置定时器变量
			timerId = null;
		}, time);
	};
}

export function dataURItoBlob(dataURI: string) {
	//图片转成Buffer
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {
		type: mimeString
	});
}

export const getCustomerUserId = (clientId: string, member: any) => {
	const data = member.find((item: any) => item.id === clientId);
	return data && data.user.id;
};

/** 格式化时间, 秒转 00：00 ：00 */
export const formatScends = (scends: number): string => {
	const h = parseInt((scends / 3600).toString()); //小时
	const m = parseInt(((scends % 3600) / 60).toString()); //拿到分钟数
	const s = parseInt(((scends % 3600) % 60).toString()); //拿到秒数
	return `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`;
};

export function formatDuring(timeStamp: number) {
	let hours: any = parseInt(((timeStamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) as unknown as string);
	let minutes: any = parseInt(((timeStamp % (1000 * 60 * 60)) / (1000 * 60)) as unknown as string);
	let seconds: any = parseInt(((timeStamp % (1000 * 60)) / 1000) as unknown as string);
	hours = hours < 10 ? '0' + hours : hours;
	minutes = minutes < 10 ? '0' + minutes : minutes;
	seconds = seconds < 10 ? '0' + seconds : seconds;
	return hours + ':' + minutes + ':' + seconds;
}

/**
+ * 比较2个数组，根据id来比较，获取新增和删除的元素
+ * @param {*} arrayA 
+ * @param {*} arrayB 
+ * @returns 
+ */
export function compareArraysWithId(arrayA:any, arrayB:any) {
	const addedElements = [];
	const deletedElements = [];
	const idMap = {};

	// 创建idMap来存储数组A的对象id
	for (const element of arrayA) {
		idMap[element.id] = element;
	}

	// 比较数组B中的每个元素与idMap中的元素
	for (const element of arrayB) {
		if (!(element.id in idMap)) {
			// 如果数组B中的元素不在idMap中，则表示它是一个新元素
			addedElements.push(element);
		} else {
			// 否则将元素从idMap中删除
			delete idMap[element.id];
		}
	}

	// 剩余的idMap元素表示在数组A中但不在数组B中的元素
	for (const id in idMap) {
		deletedElements.push(idMap[id]);
	}

	return {
		added: addedElements,
		deleted: deletedElements
	};
}

/**
 * 从url中提取文件类型
 * @param url 
 * @returns 
 */
export const getFileTypeFromText = (url: string) => {
	// url 不以 http 开头，返回 text
	if (!url || !url.startsWith("http")) {
	  return "text";
	}
	// Extract the file extension
	const extension: string = url.split(".").pop()?.toLowerCase() || '';
	console.log('extension', extension);
  
	// Define the file type categories
	const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "svg", "webp"];
	const videoExtensions = ["mp4", "avi", "mov", "wmv", "flv", "mkv", "webm"];
	const pdfExtensions = ["pdf"];
  
	// Determine the file type
	if (imageExtensions.includes(extension)) {
	  return "image";
	} else if (videoExtensions.includes(extension)) {
	  return "video";
	} else if (pdfExtensions.includes(extension)) {
	  return "pdf";
	} else {
	  return "text";
	}
  };

  export const appendToken = (url: string) => {
	if (!url) return url;
	// 如果url中已经有token，则不再追加	token
	if (url.indexOf('token=') > -1) {
		return url;
	}
	if (url.startsWith('blob:')) {
		return url;
	}
	const separator = url.includes('?') ? '&' : '?';
	const token = AgentService.getToken();
	return `${url}${separator}token=${token}`;
};

export const removeToken = (url: string) => {
	if (!url) {
		return url;
	}
	// 如果url中没有token
	if (url.indexOf('token=') < 0) {
		return url;
	}
	const token = AgentService.getToken();
	if (url.includes(`&token=`)) {
		return url.replace(`&token=${token}`, '');
	}
	return url.replace(`?token=${token}`, '');
};